import 'package:auto_size_text/auto_size_text.dart';
import 'package:concierge/app/common/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class AnalysisCardColumn {
  final String title;
  final String key;
  final Widget Function(dynamic value, Map<String, dynamic> record, int index)?
  render;

  const AnalysisCardColumn({
    required this.title,
    required this.key,
    this.render,
  });
}

class AnalysisCard extends StatelessWidget {
  final String title;
  final String content;
  final List<String> contents;
  final String description;
  final String rightText;
  final VoidCallback? onRightPressed;
  final List<AnalysisCardColumn> columns;
  final List<Map<String, dynamic>> dataSource;

  const AnalysisCard({
    super.key,
    this.title = '',
    this.content = '',
    this.description = '',
    this.rightText = '',
    this.onRightPressed,
    this.columns = const [],
    this.contents = const [],
    this.dataSource = const [],
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = context.theme.colorScheme;
    final textTheme = context.theme.textTheme;
    List<Widget> contentChildren = [];
    for (int i = 0; i < contents.length; i++) {
      contentChildren.add(
        Text(
          contents[i],
          style: textTheme.bodyMedium?.copyWith(color: colorScheme.tertiary),
        ),
      );
      if (i != contents.length - 1) {
        contentChildren.add(SizedBox(height: 10.h));
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            Expanded(
              child: Text(
                title,
                style: textTheme.headlineMedium?.copyWith(
                  color: colorScheme.onPrimary,
                ),
              ),
            ),
            rightText.isNotEmpty
                ? InkWell(
                    onTap: onRightPressed,
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    splashFactory: NoSplash.splashFactory,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          rightText,
                          style: textTheme.bodyMedium?.copyWith(
                            color: colorScheme.primaryFixed,
                          ),
                          textAlign: TextAlign.end,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        Icon(
                          Icons.chevron_right_rounded,
                          size: 14.w,
                          color: colorScheme.primaryFixed,
                        ),
                      ],
                    ),
                  )
                : const SizedBox(),
          ],
        ),
        // Row(
        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //   children: [
        //     Text(
        //       title,
        //       style: textTheme.headlineMedium?.copyWith(
        //         color: colorScheme.onPrimary,
        //       ),
        //     ),
        //     Expanded(
        //         child: rightText.isNotEmpty
        //             ? InkWell(
        //                 onTap: onRightPressed,
        //                 splashColor: Colors.transparent,
        //                 highlightColor: Colors.transparent,
        //                 splashFactory: NoSplash.splashFactory,
        //                 child: Row(
        //                   crossAxisAlignment: CrossAxisAlignment.center,
        //                   mainAxisAlignment: MainAxisAlignment.end,
        //                   children: [
        //                     Flexible(
        //                       child: Text(
        //                         rightText,
        //                         style: textTheme.bodyMedium?.copyWith(
        //                           color: colorScheme.primaryFixed,
        //                         ),
        //                         textAlign: TextAlign.end,
        //                         overflow: TextOverflow.ellipsis,
        //                         maxLines: 1,
        //                       ),
        //                     ),
        //                     Icon(
        //                       Icons.chevron_right_rounded,
        //                       size: 14.w,
        //                       color: colorScheme.primaryFixed,
        //                     ),
        //                   ],
        //                 ),
        //               )
        //             : const SizedBox()),
        //   ],
        // ),
        SizedBox(height: 10.h),
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: colorScheme.primaryContainer,
            borderRadius: BorderRadius.circular(AppTheme.cornerLarge.w),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              content.isNotEmpty
                  ? Text(
                      content,
                      style: textTheme.bodyMedium?.copyWith(
                        color: colorScheme.tertiary,
                      ),
                    )
                  : const SizedBox(),
              ...contentChildren,
              _buildCard(colorScheme, textTheme),
              description.isNotEmpty
                  ? Text(
                      description,
                      style: textTheme.labelSmall?.copyWith(
                        color: colorScheme.tertiary,
                      ),
                    )
                  : const SizedBox(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildCard(ColorScheme colorScheme, TextTheme textTheme) {
    if (columns.isEmpty) {
      return const SizedBox();
    }
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(AppTheme.cornerLarge.w),
          border: Border.all(color: colorScheme.outline),
        ),
        clipBehavior: Clip.antiAlias,
        child: Column(
          children: [
            _buildColumns(colorScheme, textTheme),
            _buildRows(colorScheme, textTheme),
          ],
        ),
      ),
    );
  }

  Widget _buildColumns(ColorScheme colorScheme, TextTheme textTheme) {
    int index = 0;
    return Row(
      children: columns.map((c) {
        BorderRadiusGeometry? borderRadius;
        BoxBorder? border;
        if (index != columns.length - 1) {
          border = Border(right: BorderSide(color: colorScheme.outline));
        }
        if (index == 0) {
          borderRadius = BorderRadius.only(
            topLeft: Radius.circular(AppTheme.cornerLarge.w),
          );
        }
        if (index == columns.length - 1) {
          borderRadius = BorderRadius.only(
            topRight: Radius.circular(AppTheme.cornerLarge.w),
          );
        }
        final widget = Expanded(
          child: Container(
            alignment: Alignment.center,
            height: 28.h,
            decoration: BoxDecoration(
              color: colorScheme.outline,
              border: border,
              borderRadius: borderRadius,
            ),
            child: Text(
              c.title,
              style: textTheme.labelMedium?.copyWith(
                color: colorScheme.primary,
              ),
            ),
          ),
        );
        index++;
        return widget;
      }).toList(),
    );
  }

  Widget _buildRows(ColorScheme colorScheme, TextTheme textTheme) {
    int index = 0;
    int itemIndex = 0;
    List<Map<String, dynamic>> source = dataSource;
    if (source.isEmpty) {
      source = [columns.asMap().map((key, value) => MapEntry(value.key, -1))];
    }
    return Column(
      children: source.map((data) {
        final widget = Container(
          decoration: BoxDecoration(
            border: index != dataSource.length - 1
                ? Border(bottom: BorderSide(color: colorScheme.outline))
                : null,
          ),
          child: Row(
            children: columns.map((c) {
              final value = data[c.key] ?? -1;
              BoxBorder? border;
              if (itemIndex != columns.length - 1) {
                border = Border(right: BorderSide(color: colorScheme.outline));
              }
              final child = Expanded(
                child: Container(
                  alignment: Alignment.center,
                  height: 28.h,
                  decoration: BoxDecoration(border: border),
                  child:
                      c.render?.call(value, data, index) ??
                      AutoSizeText(
                        value == -1 ? '--' : value.toString(),
                        style: textTheme.labelMedium?.copyWith(
                          color: colorScheme.primary,
                        ),
                        maxLines: 1,
                        minFontSize: 9,
                        textAlign: TextAlign.center,
                      ),
                ),
              );
              itemIndex++;
              return child;
            }).toList(),
          ),
        );
        index++;
        return widget;
      }).toList(),
    );
  }
}
